<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Category;

class CategoryController extends Controller
{
    //
    public function index(){
        $categories = Category::paginate(15);
        return view('admin/category/index')->with('categories', $categories);
    }

    public function create(){
        return view('admin/category/create');
    }

    public function store(Request $request){
        $this->validate($request, [
            'title'=>'required|unique:categorys|max:255',
            'body'=>'required',
        ]);

        $category = new Category();
        $category->title = $request->get('title');
        $category->body = $request->get('body');
        $category->user_id = $request->user()->id;

        if($category->save()){
            return redirect('admin/category');
        }else{
            return redirect()->withErrors('新增失败！');
        }
    }

    public function show($id){
        $category = Category::with('hasManyComments')->find($id); 
        $title = $category->title;
        return view('admin/category/show', ['category' => $category, 'title' => $title]);
    }

    public function edit($id) { 
        $category = Category::find($id); 
        return view('admin/category/edit')->with('category', $category); 
    }

    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'title' => 'required|unique:categorys,title,'.$id.'|max:255',
            'body' => 'required', 
        ]);

        $category = Category::find($id);
        $category->title = $request->get('title');
        $category->body = $request->get('body');

        if ($category->save()) {
            return redirect('admin/category');
        } else {
            return redirect('admin/category')->withErrors('更新失败！');
        }
    }

    public function destroy($id){
        $category = Category::find($id);  
        if($category->delete()){
            return redirect('admin/category')->withErrors('删除成功！');
        }else{
            return redirect('admin/category')->withErrors('删除失败！');
        }
    }
    
}
